package com.sdy.resdir.mq.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.resdir.biz.model.*;
import com.sdy.resdir.biz.service.*;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.DeptDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.xml.crypto.Data;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.stream.Collectors.joining;


/**
 * @author cgj
 */
@Service
@Slf4j
public class ApprovalMsgFacade {

    @Autowired
    private RdResourceApplicationDetailService radService;
    @Autowired
    private RdImplementationOrderService rdImpOrderService;
    @Autowired
    private RdResourceDirService rdResourceDirService;
    @Autowired
    private RdResManagementService resManaService;
    @Autowired
    private RdResForOnlineService rdResForOnlineService;
    @Autowired
    private RdIpUpdateApplicationService ipApplyOrderService;
    @Autowired
    private UserQueryApi userQueryApi;
    @Value("${res.dept.code}")
    private String deptCode;
    @Autowired
    private RdIpImpleOrderService ipImpleOrderService;

    public Boolean setOrderAndResIdState(String orderInfo) {
        try {
            // 准备需要的数据
            Map<String, Object> map = JSON.parseObject(orderInfo, Map.class);
            String applyNumChild = (String) map.get("applicationNum");
            Integer state = (Integer) map.get("gsOrderState");
            String resId = (String) map.get("resId");
            if (resId.contains("[资源目录]")) {
                // 获取数据局部门id,放入需要生成的实施工单中
                DeptDto dept = userQueryApi.getDeptByCode(deptCode);
                if (resId.contains("[资源目录]-IP")) {
                    boolean updateState = ipApplyOrderService.update(Wrappers.<RdIpUpdateApplication>lambdaUpdate().eq(RdIpUpdateApplication::getApplyNum, applyNumChild).set(RdIpUpdateApplication::getCurrentState, state));
                    if (6 == state) {
                        RdIpUpdateApplication one = ipApplyOrderService.getOne(Wrappers.<RdIpUpdateApplication>lambdaQuery().eq(RdIpUpdateApplication::getApplyNum, applyNumChild));
                        String userName = userQueryApi.getUser(one.getApplyUserId()).getName();
                        // 创建IP实施工单对象
                        RdIpImpleOrder rdIpImpleOrder = new RdIpImpleOrder()
                                .setAppId(one.getAppId())
                                .setCreateTime(new Date())
                                .setDeptId(dept.getId())
                                .setOrderNo(System.currentTimeMillis() + "")
                                .setApplyNum(applyNumChild)
                                .setIpId(one.getIpId())
                                .setType(one.getType())
                                .setState(0)
                                .setUserId(one.getApplyUserId());
                        boolean save = ipImpleOrderService.save(rdIpImpleOrder);
                        if (!save) {
                            log.error("通过MQ消息生成IP实施工单时出现错误");
                        }
                    }
                    if (!updateState) {
                        log.error("通过MQ消息更新ip修改申请单状态时出现错误");
                    }
                }
                if (resId.contains("[资源目录]-已归集")) {
                    // 准备资源id(主键)
                    String replaceResId = resId.replace("[资源目录]-已归集", "");
                    Integer intResId = Integer.valueOf(replaceResId);
                    // 查询该资源信息
                    RdResourceDir oneDir = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery()
                            .eq(RdResourceDir::getId, intResId));
                    // 更新本地订单状态
                    LambdaUpdateWrapper<RdResourceApplicationDetail> updateState = new LambdaUpdateWrapper<>();
                    updateState.eq(StringUtil.isNotBlank(applyNumChild), RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                            .isNull(RdResourceApplicationDetail::getVersionNum)
                            .set(RdResourceApplicationDetail::getState, state);
                    RdResourceApplicationDetail one = radService.getOne(Wrappers.<RdResourceApplicationDetail>lambdaQuery()
                            .eq(RdResourceApplicationDetail::getApplyNumChild, applyNumChild));
                    Boolean updateStateLocal = radService.update(updateState);
                    Assert.notTrue(updateStateLocal, "通过MQ接受的指令，修改已上线订单状态时出错，请打开（ApprovalMsgFacade.java）核查");
                    if (state == 6) {
                        // 如果审批通过，添加到实施工单
                        String impOrder = String.valueOf(System.currentTimeMillis());
                        RdImplementationOrder rdImplementationOrder = new RdImplementationOrder();
                        rdImplementationOrder
                                .setApplyNum(applyNumChild)
                                .setResName(oneDir.getResName())
                                .setResUniqueCode(oneDir.getResCode())
                                .setImplementationWorkOrder(impOrder)
                                .setResType(oneDir.getResType())
                                .setResourceConsumers(one.getApplyDeptName())
                                .setApprovalTime(new Date())
                                .setResState(oneDir.getResState())
                                .setUserId(one.getApplyUserId())
                                .setResId(one.getResId())
                                .setImplementationState(0)
                                .setDeptId(dept.getId())
                                .setOrderType(1)
                                .setPreselectResType(one.getResType());
                        boolean save = rdImpOrderService.save(rdImplementationOrder);

                        // 通过后，发放给个人（新增数据到rd_res_management）
                        LambdaQueryWrapper<RdResourceApplicationDetail> selectDetail = new LambdaQueryWrapper<>();
                        selectDetail.eq(RdResourceApplicationDetail::getApplyNumChild, applyNumChild)
                                .isNull(RdResourceApplicationDetail::getVersionNum);
                        RdResourceApplicationDetail oneDetail = radService.getOne(selectDetail);
                        RdResManagement rdResManagement = new RdResManagement();
                        rdResManagement.setResId(oneDetail.getResId())
                                .setDeptId(one.getDeptId())
                                .setCreateTime(new Date())
                                .setSrcDeptName(oneDir.getResPowerDept())
                                .setUserId(oneDetail.getApplyUserId());
                        boolean saveResMana = resManaService.save(rdResManagement);
                        Assert.isTrue(!save || !saveResMana, "新增实施工单出错 || 通过后新增到rd_res_management");
                    } else {
                        // 驳回是仅更新订单状态
                    }
                } else if (resId.contains("[资源目录]-未归集")) {
                    // 准备资源id(主键)
                    String replaceResId = resId.replace("[资源目录]-未归集", "");
                    Integer intResId = Integer.valueOf(replaceResId);
                    // 查询该资源是否已上线
                    RdResourceDir oneDir = rdResourceDirService.getOne(Wrappers.<RdResourceDir>lambdaQuery()
                            .eq(RdResourceDir::getId, intResId));
                    // 更新本地订单状态
                    LambdaUpdateWrapper<RdResForOnline> updateOnlineState = new LambdaUpdateWrapper<>();
                    updateOnlineState.eq(StringUtil.isNotBlank(applyNumChild), RdResForOnline::getApplicationNum, applyNumChild)
                            .isNull(RdResForOnline::getVersionNum)
                            .set(RdResForOnline::getState, state);
                    RdResForOnline oneOnline = rdResForOnlineService.getOne(Wrappers.<RdResForOnline>lambdaQuery().eq(RdResForOnline::getApplicationNum, applyNumChild));
                    // 更新本地订单状态
                    Boolean updateOnlineStateLocal = rdResForOnlineService.update(updateOnlineState);
                    Assert.notTrue(updateOnlineStateLocal, "通过MQ接受的指令，修改未上线订单状态时出错，请打开（ApprovalMsgFacade.java）核查");
                    if (state == 6) {
                        // 如果审批通过，添加到实施工单
                        String impOrder = String.valueOf(System.currentTimeMillis());
                        RdImplementationOrder rdImplementationOrder = new RdImplementationOrder();
                        rdImplementationOrder
                                .setApplyNum(applyNumChild)
                                .setResName(oneDir.getResName())
                                .setResUniqueCode(oneDir.getResCode())
                                .setImplementationWorkOrder(impOrder)
                                .setResType(oneDir.getResType())
                                .setResourceConsumers(oneOnline.getApplyDeptName())
                                .setApprovalTime(new Date())
                                .setResState(oneDir.getResState())
                                .setUserId(oneOnline.getApplyUserId())
                                .setResId(oneOnline.getResId())
                                .setDeptId(dept.getId())
                                .setImplementationState(0)
                                .setOrderType(2)
                                .setPreselectResType(oneDir.getPreselectResType());
                        boolean save = rdImpOrderService.save(rdImplementationOrder);
                        Assert.notTrue(save, "上线生成实施工单时出错");
                    }
                }
                log.info("审批通过完成");
                return true;
            }
        } catch (Exception e) {
            log.error("根据流程审批模块发送的消息更新订单资源状态时出现错误", e);
        }
        return true;
    }

}

